import os
import json
import uuid
from typing import Optional
from fastapi import HTTPException
from aiofiles import open as aio_open

# 异步加载会话历史
async def load_session_history(session_id: str, log_dir: str = "session_logs"):
    log_file = os.path.join(log_dir, f"session_{session_id}.log")
    if not os.path.exists(log_file):
        return []
    async with aio_open(log_file, 'r', encoding='utf-8') as f:
        lines = await f.readlines()
        return [json.loads(line.strip()) for line in lines if line.strip()]

# 异步追加写入日志
async def append_to_log(session_id: str, message: dict, log_dir: str = "session_logs"):
    os.makedirs(log_dir, exist_ok=True)
    log_file = os.path.join(log_dir, f"session_{session_id}.log")
    async with aio_open(log_file, 'a', encoding='utf-8') as f:
        await f.write(json.dumps(message, ensure_ascii=False) + '\n')

def get_user_questions(log_file: str):
    user_questions = []
    if os.path.exists(log_file):
        with open(log_file, 'r', encoding='utf-8') as f:
            for line in f:
                if line.strip():
                    try:
                        data = json.loads(line.strip())
                        if data.get("role") == "user":
                            user_questions.append(data.get("content"))
                    except json.JSONDecodeError:
                        continue
    return user_questions